
package com.wangzha.business.ctrl;

import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Record;
import com.wangzha.business.service.Record_recordGroupService;
import com.wangzha.business.service.UserRecordGroupService;
import com.wangzha.business.service.UserUploadFileService;
import com.wangzha.common.base.BaseController;
import com.wangzha.common.model.Record_recordGroup;
import com.wangzha.common.model.UserRecordGroup;
import com.wangzha.common.model.UserUploadFile;
import com.wangzha.common.vo.Grid;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 录制分组
 */
@Path("/record/group")
public class RecordGroupController extends BaseController {

    @Inject
    Record_recordGroupService record_recordGroupService;

    @Inject
    UserUploadFileService userUploadFileService;

    @Inject
    UserRecordGroupService userRecordGroupService;

    public void index() {
        render("index.html");
    }

    public void list() {
        Record record = new Record();
        record.set("user_code", getVisitor().getCode());
        record.set("name", getPara("name"));

        String categoryName = getPara("categoryName");

        Grid grid = null;
        if (StringUtils.isEmpty(categoryName)) {
            grid = userRecordGroupService.queryForListEq(getParaToInt("pageNumber", 1),
                    getParaToInt("pageSize", 10), record);
        } else {
            grid = userRecordGroupService.queryForListEq(getParaToInt("pageNumber", 1),
                    9999999, record);
        }
        List<Record> userRecordGroupList = (List<Record>) grid.getList();
        if (CollectionUtils.isEmpty(userRecordGroupList)) {
            renderJson(new Grid());
            return;
        } else {
            if (StringUtils.isNotBlank(categoryName)) {
                List<Long> parentGroupIdList = userRecordGroupList.stream().map(e -> e.getLong("parent_group_id")).collect(Collectors.toList());
                List<Record_recordGroup> record_recordGroupList = record_recordGroupService.findByGroupIds(parentGroupIdList);

                Map<Long, List<Record_recordGroup>> record_recordGroupListMap =  record_recordGroupList.stream().collect(Collectors.groupingBy(Record_recordGroup::getRecordGroupId));
                List<Long> result =  new ArrayList<Long>();
                for (Long key : record_recordGroupListMap.keySet()) {
                    List<Record_recordGroup> record_recordGroups = record_recordGroupListMap.get(key);
                    List<String> recordIds = record_recordGroups.stream().map(Record_recordGroup :: getRecordId)
                            .map(x -> String.valueOf(x)).collect(Collectors.toList());
                    List<UserUploadFile> userUploadFileList = (List<UserUploadFile>) userUploadFileService.findByIds(recordIds);
                    if ("其他".equals(categoryName))  {
                        Map<String, List<UserUploadFile>> list = userUploadFileList.stream().collect(Collectors.groupingBy(UserUploadFile::getAppName));
                        if (list.size() >= 2) {
                            result.add(key);
                        }
                    } else {
                        for (int i=0; i < userUploadFileList.size(); i++) {
                            if (!categoryName.equals(userUploadFileList.get(i).getAppName())) {
                                break;
                            }
                            if (i == userUploadFileList.size() - 1) {
                                result.add(key);
                            }
                        }
                    }
                }
                userRecordGroupList = userRecordGroupList.stream().filter(e -> result.contains(e.getLong("parent_group_id"))).collect(Collectors.toList());
                grid.setList(userRecordGroupList);
                renderJson(grid);
            } else {
                renderJson(grid);
            }
        }
    }

    public void add() {
        render("add.html");
    }

    public void save() {
        UserRecordGroup entity = getBean(UserRecordGroup.class);
        entity.setUserCode(getVisitor().getCode());
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        entity.save();

        entity.setParentGroupId(entity.getId());
        entity.update();

        setAttr("userRecordGroup", entity);
        render("add.html");
    }


    public void edit() {
        setAttr("userRecordGroup", userRecordGroupService.findById(getPara(0)));
        render("edit.html");
    }

    public void update() {
        UserRecordGroup entity = getBean(UserRecordGroup.class);
        entity.setUpdateTime(new Date());
        entity.update();
        setAttr("userRecordGroup", entity);
        render("edit.html");
    }

    public void delete() {
        if (CollectionUtils.isNotEmpty(getIds())) {
            for (String id : getIds()) {
                UserRecordGroup recordGroup = userRecordGroupService.findByParentGroupIdAndUserCode(getVisitor().getCode(), Long.valueOf(id));
                if (recordGroup != null) {
                    recordGroup.delete();
                } else {
                    userRecordGroupService.deleteByUserCodeAndGroupId(getVisitor().getCode(), Long.valueOf(id));
                }
            }
        }
        renderJson(suc());
    }

    public void distributeRecord() {
        UserRecordGroup userRecordGroup = (UserRecordGroup) userRecordGroupService.findById(getPara("id"));
        setAttr("groupId", userRecordGroup.getId());
        render("distribute_record.html");
    }

    /**
     * 查询未分组用户列表
     */
    public void queryUserListNotInRecordGroup() {
        int pageNumber = getParaToInt("pageNumber",1);
        int pageSize = getParaToInt("pageSize",10);
        List<Record_recordGroup> record_recordGroups = record_recordGroupService.findByGroupId(getParaToLong("groupId"));
        List<Long> recordIds = record_recordGroups.stream().map(e -> e.getRecordId()).collect(Collectors.toList());
        renderJson(userUploadFileService.queryListNotInIds(pageNumber, pageSize, recordIds, getVisitor().getCode(), getPara("name")));
    }

    /**
     * 查询已经分组场景列表
     */
    public void queryUserListInRecordGroup() {
        int pageNumber = getParaToInt("pageNumber",1);
        int pageSize = getParaToInt("pageSize",10);
        List<Record_recordGroup> record_recordGroups = record_recordGroupService.findByGroupId(getParaToLong("groupId"));
        List<Long> recordIds = record_recordGroups.stream().map(e -> e.getRecordId()).collect(Collectors.toList());
        renderJson(userUploadFileService.queryListInIds(pageNumber, pageSize, recordIds, getVisitor().getCode(), getPara("name")));
    }

    public void addGroup() {
        UserRecordGroup userRecordGroup = (UserRecordGroup) userRecordGroupService.findById(getPara("groupId"));
        Record_recordGroup record_recordGroup = new Record_recordGroup();
        record_recordGroup.setRecordGroupId(getLong("groupId"));
        record_recordGroup.setRecordId(getLong("recordId"));
        record_recordGroup.setParentGroupId(userRecordGroup.getParentGroupId());
        if (record_recordGroup.save()) {
            renderJson(suc("添加成功"));
        } else {
            renderJson(fail("添加失败"));
        }
    }

    public void removeGroup() {
        if (record_recordGroupService.deleteByGroupIdAndRecordId(getLong("groupId"), getLong("recordId"))) {
            renderJson(suc("移出成功"));
        } else {
            renderJson(fail("移出失败"));
        }
    }

    public void getGroupCategory() {
        List<String> categoryList = new ArrayList<>();
        List<UserRecordGroup> userRecordGroupList = userRecordGroupService.findByUserCode(getVisitor().getCode());
        if (CollectionUtils.isNotEmpty(userRecordGroupList)) {
            for (UserRecordGroup recordGroup : userRecordGroupList) {
                List<Record_recordGroup> record_recordGroupList = record_recordGroupService.findByGroupId(recordGroup.getParentGroupId());
                if (CollectionUtils.isNotEmpty(record_recordGroupList)) {
                    List<String> recordIds = record_recordGroupList.stream().map(Record_recordGroup :: getRecordId)
                            .map(x -> String.valueOf(x)).collect(Collectors.toList());
                    List<UserUploadFile> userUploadFileList = (List<UserUploadFile>) userUploadFileService.findByIds(recordIds);

                    Map<String, UserUploadFile> userUploadFileMap = userUploadFileList.stream()
                            .collect(Collectors.toMap(UserUploadFile::getAppName, Function.identity(),
                                (value1, value2) -> {
                                return value2;
                            }
                    ));

                    if (MapUtils.isNotEmpty(userUploadFileMap)) {
                        if (userUploadFileMap.size() == 1) {
                            Object appName = userUploadFileMap.keySet().toArray()[0];
                            if (appName != null && StringUtils.isNotBlank(appName.toString())) {
                                categoryList.add(appName.toString());
                            }
                        } else {
                            categoryList.add("其他");
                        }
                    }
                }
            }
        }
        categoryList = categoryList.stream().distinct().collect(Collectors.toList());
        renderJson(categoryList);
    }
}

